﻿using Modules.Cms;
using Modules.Project;
using Modules.Project.Entitys;
using Modules.Reports;
using PmSoft.Quartz;
using Quartz;

namespace ManagementApi.Jobs;

/// <summary>
/// 推送项目管理人员考勤率到一体化平台
/// </summary>
[DisallowConcurrentExecution]//不可并行执行
[JobDescription("0 0 00 1 * ?")]//每月1日01:00:00执行一次(必须要等项目月报表同步完成后执行)
//[JobDescription("0 */1 * * * ?")]//测试1分钟执行1次
public class PushManagerCheckinRateJob : IJob
{
    private readonly ProjectCheckinPushLogService projectCheckinPushLogService;
    private readonly CmsSupportService cmsSupportService;
    private readonly ILogger logger;

    public PushManagerCheckinRateJob(ProjectCheckinPushLogService projectCheckinPushLogService, CmsSupportService cmsSupportService, ILogger<PushManagerCheckinRateJob> logger)
    {
        this.projectCheckinPushLogService = projectCheckinPushLogService;
        this.cmsSupportService = cmsSupportService;
        this.logger = logger;
    }



    /// <summary>
    /// 执行
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    public Task Execute(IJobExecutionContext context)
    {
        int month = Convert.ToInt32(DateTime.Now.AddMonths(-1).ToString("yyyyMM"));
        IEnumerable<int> projectIds;
        while ((projectIds = projectCheckinPushLogService.GetProjectIdsInNoUpdate(month)).Count() > 0)
        {
            foreach (int projectId in projectIds)
            {
                try
                {
                    cmsSupportService.ProjectPersonAttendanceInfos(projectId,month);
                }
                catch (Exception ex)
                {
                    logger.LogError(ex, "推送项目管理人员考勤率到一体化平台执行失败，projectId={0}，错误消息={1}", projectId, ex.Message);
                    throw;
                }
            }
        }
        return Task.CompletedTask;
    }
}
